import Vue from "vue";
import Vuex from "vuex";
import user from "./modules/user"
import _ from "lodash";

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        //这里放全局参数
        user: {},
        token: localStorage.getItem('token') ? localStorage.getItem('token') : '',
    },
    mutations: {
        //这里是set方法
        setUser(state, user) {
            var _user = _.merge({}, state.user);
            if (!_.size(_user)) {
                _user = {};
            }
            _.each(user, function(value, key) {
                _user[key] = value;
            })
            localStorage.setItem("user", JSON.stringify(_user));
            state.user = _user;
        },
        setToken(state, token) {
            localStorage.setItem("token", token);
            state.token = token;
        },
        logOut(state) {
            localStorage.clear();
            state.user = {};
            state.token = null
        }


    },
    actions: {},
    modules: {
        //这里是我自己理解的是为了给全局变量分组，所以需要写提前声明其他store文件，然后引入这里
        user
    },
    getters: {
        user(state) {
            if (!_.size(state.user)) {
                var user = {};
                var u = JSON.parse(window.localStorage.getItem("user"));
                if (u) {
                    user = u;
                }
                localStorage.setItem("user", JSON.stringify(user));
                state.user = user;
                return user;
            }
            return state.user
        },
        token(state) {
            return state.token
        }
    },


});